import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, getTimeStamp, setTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {},
    userId: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  }

}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    const { mobile, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile: mobile.trim(), password: password }).then(response => {
        // const { data } = response
        commit('SET_TOKEN', response)
        setToken(response)

        /* 存储时间戳===记录什么时间获取的token */
        setTimeStamp(Date.now())
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      return getInfo().then(response => {
        const { username: name, roles: { menus } } = response

        if (!response) {
          return reject('Verification failed, please Login again.')
        }
        // console.log(name,4444)
        /* 存储权限点 */
        /*
        将路由权限点存储起来  有2中方式 字节存储 或者存储到permission.js

        */
        // commit('SET_ROUTES', menus)

        commit('SET_NAME', name)
        commit('SET_USERINFO', response)
        // commit('SET_AVATAR', avatar)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      //   removeToken() // must remove  token  first
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })

      try {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      } catch (error) {
        reject(error)
      }
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

